package jmine.tec.sync.channel;

import java.io.IOException;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;

import jmine.tec.sync.DataPushChannel;
import bancosys.tec.rtm.exception.ExceptionPersister;

/**
 * {@link DataPushChannel} que empurra os dados para um servidor JMS
 * 
 * @author takeshi
 */
public class JMSDataPushChannel extends AbstractDataPushChannel implements DataPushChannel {

    private ConnectionFactory connectionFactory;

    private Queue destination;

    private ExceptionPersister errorMonitor;

    /**
     * {@inheritDoc}
     */
    public void pushCommandsAsBytes(byte[] data) throws IOException {
        try {
            Connection conn = this.getConnectionFactory().createConnection();
            try {
                Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer prod = session.createProducer(getDestination());
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(data);
                prod.send(bytesMessage);
            } finally {
                if (conn != null) {
                    conn.close();
                }
            }
        } catch (JMSException e) {
            if (errorMonitor != null) {
                errorMonitor.monitor(e);
            }
            throw new IOException(e.getMessage());
        }
    }

    /**
     * @return the connectionFactory
     */
    public ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    /**
     * @param connectionFactory the connectionFactory to set
     */
    public void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    /**
     * @return the destination
     */
    public Queue getDestination() {
        return destination;
    }

    /**
     * @param destination the destination to set
     */
    public void setDestination(Queue destination) {
        this.destination = destination;
    }

    /**
     * @return the errorMonitor
     */
    public ExceptionPersister getErrorMonitor() {
        return errorMonitor;
    }

    /**
     * @param errorMonitor the errorMonitor to set
     */
    public void setErrorMonitor(ExceptionPersister errorMonitor) {
        this.errorMonitor = errorMonitor;
    }

}
